package com.jweb.framework.id;

import java.util.Calendar;
import java.util.Locale;
import java.util.TimeZone;


public class TimeServiceImpl implements TimeService {
	
	private long remoteTim ; // 
	private long localTim ;  // 
	private int sychronizeInterval = 60000 ; // 
	private TimeZone timeZone ;  // 
	private Locale locale ;  // 
	private int firstDayOfWeek = 2 ; // 
	
	public void setSychronizeInterval(int i){
		this.sychronizeInterval = i ;
	}
	
	public void setTimeZone(TimeZone tz){
		this.timeZone = tz ;
	}
	
	public void setLocale(Locale l){
		this.locale = l ;
	}
	
	public void setFirstDayOfWeek(int f){
		this.firstDayOfWeek = f ;
	}
	
	public final void reset(){
		this.remoteTim = remoteTimeMillis();
		this.localTim = localTimeMillis();
	}
	
	protected long localTimeMillis(){
		return System.currentTimeMillis();
	}
	
	protected long remoteTimeMillis(){
		return System.currentTimeMillis() ;
	}
	
	private long dueTim(){
		return System.currentTimeMillis() - localTim ;
	}
	
	public final synchronized long currentTimeMillis(){
		long l = dueTim();
		if(l > this.sychronizeInterval){
			reset() ;
		}
		return this.remoteTim + dueTim() ;
	}
	
	public final boolean isCutoff(int i , long l){
		long l1 = currentTimeMillis();
		return isCutoff(i , l1 , l);
	}
	
	public final boolean isCutoff(int i , long l , long l1){
		return getValue(i , l) - getValue(i , l1) > 0;
	}
	
	
	private Calendar getCalendar(){
		Calendar calendar = null ;
		if((this.timeZone!=null) && (this.locale != null)){
			calendar = Calendar.getInstance(this.timeZone , this.locale);
		}
		else  if(this.timeZone != null){
			calendar = Calendar.getInstance(this.timeZone);
		}
		else if(this.locale != null){
			calendar = Calendar.getInstance(this.locale);
		}
		else {
			calendar = Calendar.getInstance() ;
		}
		calendar.setFirstDayOfWeek(this.firstDayOfWeek);
		return calendar ;
	}
	
	
	private int getValue(int i , long l){
		Calendar calendar = getCalendar();
		calendar.setTimeInMillis(l);
		return calendar.get(i);
	}
	
}
